package com.jiangjun.fetch.util;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.jiangjun.fetch.FetchWeibo;
import com.jiangjun.fetch.Weibo;
import com.jiangjun.fetch.common.ImageWeibo;
import com.jiangjun.fetch.mongo.MongoDBSupport;
import com.jiangjun.fetch.scale.ImageImpl;
import com.jiangjun.fetch.scale.Scale4Weibo;
import com.jiangjun.fetch.scale.ScaleByIm4java;
import com.mongodb.BasicDBObject;

public class FetchWeiboUtil {

	public static String fetchWeibo(Weibo weibo) {
		String con = "";
		String resource = "";
		String source = "2008711439";
		String access_token = "2.00xPW34Bbb2wLCd1aecc5a13bMPoQE";
		// String screen_name = "中文幽默王";
		// int uid = Integer.parseInt(weibo.getId());
		String name = weibo.getName();
		int count = 20;
		int page = 1;
		int feature = 0;
		int trim_user = 1;
		String url = "https://api.weibo.com/2/statuses/user_timeline.json?source="
				+ source
				+ "&access_token="
				+ access_token
				// + "&uid="
				// + uid
				+ "&screen_name="
				+ name
				+ "&count="
				+ count
				+ "&page="
				+ page
				+ "&feature=" + feature + "&trim_user=" + trim_user;
		HttpGet httpGet = new HttpGet(url);
		DefaultHttpClient httpClient = new DefaultHttpClient();

		try {
			HttpResponse response = httpClient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				resource = EntityUtils.toString(entity, "gb2312");

			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			httpClient.getConnectionManager().shutdown();
		}

		MongoDBSupport mongoDBSupport = MongoDBSupport.getInstance();
		JSONObject root = JSONObject.fromObject(resource);
		JSONArray array = root.getJSONArray("statuses");
		for (int i = 0; i < array.size(); i++) {
			JSONObject object = (JSONObject) array.get(i);

			String id = object.getString("id");
			// 判断是否已经存在，存在则continue
			BasicDBObject param = new BasicDBObject();
			param.put("id", id);
			if (null != mongoDBSupport.queryOneByParam(
					MongoDBSupport._FETCHWEIBO, param, null)) {
				continue;
			}
			String txt = object.getString("text");
			param = new BasicDBObject();
			param.put("title", txt);
			if (null != mongoDBSupport.queryOneByParam(
					MongoDBSupport._FETCHWEIBO, param, null)) {
				continue;
			}
			String date = object.getString("created_at");
			String imgUrl = object.getString("bmiddle_pic");
			FetchWeibo fetchWeibo = new FetchWeibo();
			fetchWeibo.setId(id);
			fetchWeibo.setParent_id(weibo.getId());
			fetchWeibo.setParent_name(weibo.getName());
			fetchWeibo.setTitle(txt);
			fetchWeibo.setTxt(txt);
			fetchWeibo.setType("0");
			fetchWeibo.setIsEnable("1");
			fetchWeibo.setDate(DateUtil.getMills(date) + "");
			StringBuffer img_path = new StringBuffer();
			if (null != imgUrl && !"".equals(imgUrl)) {
				// 走图片压缩，并保存图片
				int index = 0;
				ImageWeibo imageWeibo = new ImageWeibo();
				imageWeibo.setUrl(imgUrl);
				imageWeibo.setId(id);
				imageWeibo.setParent_id(weibo.getId());
				imageWeibo = Scale4Weibo.saveSourcePic(imageWeibo, index);
				// 压缩
				try {
					ScaleByIm4java scale = new ScaleByIm4java();
					ImageImpl imageImpl = new ImageImpl();
					String target_path = imageImpl.getPath4Weibo(id,
							weibo.getId(), imageWeibo.getSource_path(),
							imageWeibo.getType(), index, 2, 320);
					BufferedImage bi = ImageIO.read(new File(imageWeibo
							.getSource_path()));
					int sourceWidth = bi.getWidth();
					ScaleByIm4java scaleByIm4java = new ScaleByIm4java();
					double s = scaleByIm4java.getScaleByWidth(320, sourceWidth);
					if (sourceWidth <= 310) {
						s = 1.0;
					}
					scale.scale(s, imageWeibo.getSource_path(), target_path);
					img_path.append(target_path);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					continue;
				}
				fetchWeibo.setImg_path(img_path.toString());
			}
			mongoDBSupport.save(fetchWeibo.toDbObject(),
					MongoDBSupport._FETCHWEIBO);
		}
		return con;
	}
}
